<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
          <!-- 添加用户对话框 -->
          <el-dialog
            title="增加角色"
            :visible.sync="addDialogVisible"
            width="60%"
            @close="addDialogClosed"
          >
            <el-form
              :model="addForm"
              :rules="addFormRules"
              ref="addFormRef"
              label-width="100px"
              class="demo-ruleForm"
            >
              <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="addForm.roleName"></el-input>
              </el-form-item>
              <el-form-item label="角色描述" prop="roleDesc">
                <el-input v-model="addForm.roleDesc"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="addDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="addRole">确 定</el-button>
            </span>
          </el-dialog>
          <!-- 修改用户对话框 -->
          <el-dialog
            title="修改信息"
            :visible.sync="showEditVisible"
            width="60%"
            @close="editDialogClose"
          >
            <el-form
              :model="editForm"
              :rules="addFormRules"
              ref="editFormRef"
              label-width="100px"
              class="demo-ruleForm"
            >
              <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="editForm.roleName"></el-input>
              </el-form-item>
              <el-form-item label="角色描述" prop="roleDesc">
                <el-input v-model="editForm.roleDesc"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="showEditVisible = false">取 消</el-button>
              <el-button type="primary" @click="editRoleInfo">确 定</el-button>
            </span>
          </el-dialog>
        </el-col>
      </el-row>
      <el-table :data="roleslist" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom','vcenter',l1 === 0 ?'bdtop':'']"
              v-for="(item1,l1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag @close="removeRightById(scope.row,item1.id)" closable>{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!--渲染二级和三级权限-->
              <el-col :span="19">
                <el-row
                  :class="['vcenter',l2 === 0 ?'':'bdtop']"
                  v-for="(item2,l2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="8">
                    <el-tag
                      @close="removeRightById(scope.row,item2.id)"
                      type="success"
                      closable
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="16">
                    <el-row>
                      <el-tag
                        @close="removeRightById(scope.row,item3.id)"
                        v-for="(item3) in item2.children"
                        :key="item3.id"
                        closable
                        type="warning"
                      >{{item3.authName}}</el-tag>
                    </el-row>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" content="编辑" placement="top" :enterable="false">
              <el-button type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-delete" @click="removeRoleById(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配权限"
              placement="top"
              :enterable="false"
            >
              <el-button @click="showSetRightDialog(scope.row)" type="danger" icon="el-icon-setting"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog title="设置权限" :visible.sync="setRightDialogVisible" width="50%" @close="setRightDialogClosed">
      <el-tree ref="treeRef" :data="rightList" :props="treeProps"  show-checkbox node-key="id" default-expand-all :default-checked-keys="defkeys"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRight">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      addDialogVisible: false,
      showEditVisible: false,
      setRightDialogVisible: false,
      roleslist: [],
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      editForm: {
        roleName: '',
        roleDesc: '',
        roleId: ''
      },
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          { min: 2, max: 10, message: '角色名长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: false, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      rightList: [],
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      defkeys: [105, 116],
      roleId: ''
    }
  },
  created () {
    this.getRloeList()
  },
  methods: {
    async getRloeList () {
      const { data: res } = await this.$http.get('roles')
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.roleslist = res.data
      // console.log(this.roleslist)
      this.$message.success('获取角色列表成功')
    },
    async showEditDialog (id) {
      this.showEditVisible = true
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('查询角色失败')
      // console.log(res)
      this.editForm = res.data
    },
    addRole () {
      this.$refs.addFormRef.validate(async valid => {
        // console.log(valid)
        // console.log(this.addForm)
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加失败')
        }
        this.$message.success('添加成功')
        this.addDialogVisible = false
        this.getRloeList()
      })
    },
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    editRoleInfo () {
      this.$refs.editFormRef.validate(async valid => {
        // console.log(valid)
        if (!valid) return
        const { data: res } = await this.$http.put('roles/' + this.editForm.roleId, { roleName: this.editForm.roleName, roleDesc: this.editForm.roleDesc })
        if (res.meta.status !== 200) {
          this.$message.error('修改数据失败')
        }
        this.$message.success('更新工作成功')
        this.showEditVisible = false
        this.getRloeList()
      })
    },
    editDialogClose () {
      this.$refs.editFormRef.resetFields()
    },
    async removeRightById (role, rightId) {
      const res = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // console.log(res)
      if (res !== 'confirm') return this.$message.info('已取消删除')
      const { data: red } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (red.meta.status !== 200) return this.$message.error('删除权限失败')
      this.$message.info('删除权限成功')
      role.children = red.data
    },
    async removeRoleById (id) {
      const res = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // console.log(res)
      if (res !== 'confirm') return this.$message.info('已取消删除')
      const { data: red } = await this.$http.delete('roles/' + id)
      if (red.meta.status !== 200) return this.$message.error('删除用户失败')
      this.$message.info('删除用户成功')
      this.getRloeList()
    },
    async showSetRightDialog (role) {
      this.roleId = role.id
      this.setRightDialogVisible = true
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限列表失败')
      this.rightList = res.data
      // 递归求三级id
      this.getLeafKeys(role, this.defkeys)
    },

    getLeafKeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item =>
        this.getLeafKeys(item, arr))
    },
    setRightDialogClosed () {
      this.defkeys = []
    },
    async allotRight () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) return this.$message.error('分配角色失败')
      this.getRloeList()
      this.setRightDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag{
  margin: 7px;
}
.bdbottom{
  border-bottom: 1px solid skyblue;
}
.bdtop{
  border-top: 1px solid skyblue;
}
.vcenter{
  display: flex;
  align-items: center;
}
</style>
